package com.lanou3g.code0516;

import com.lanou3g.code0516.common.Constant;
import com.lanou3g.code0516.controller.Controller;
import com.lanou3g.code0516.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //校验
        String msg = "";
        User user = controller.login(username, password);
        if (user != null) {
            //登陆成功
            msg = "登陆成功";
            //把user存入session之前,把对象中的密码置空
            user.setPwd("");
            //把用户信息存到session中去
            //获取session对象
            HttpSession session = request.getSession();
            //把用户信息存到session中,注意:晚上可以把User对象,直接存入session

            session.setAttribute(Constant.Session.USER, user);
            session.setAttribute("word", "人生只有走出来的美丽");
        } else {
            //登录失败
            msg = "登录失败";
        }
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("/user/msg.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
